/**
 * 考勤管理-出勤记录
 */
import React, { Fragment } from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import moment from 'moment';
import { Form, Input, Button, Table, Card } from 'antd';
import { QuickForm, utils } from 'vv-frontend-components';
import Locale from '@/utils/locale';
import { CompanyDepartPlus } from '@/containers';
import DateRange from '@/components/DateRange';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import updateQuery from '@/utils/formValuesToQuery';
import { download } from '@/utils/utils';
import LinkTo from '@/components/LinkTo';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { withRoutePage } from '@/utils/enhanceUtils';
import { Pagination } from '@/components';

const { locale } = new Locale('stat.overtime');
const { deepTrim } = utils;

const List = ({ form, attendRecord, loading, dispatch, location, match, route }) => {
    const { query } = location;
    const { employeeName, startTime, endTime, dateType, quarter } = query;
    const { authCode } = new AuthCode(route.code);
    const { getFieldsValue } = form;
    // const [pagination, setPagination] = React.useState({ pageNo: 1, pageSize: 10 });
    const { data } = attendRecord;

    const config = [
        {
            field: 'companyDepart',
            label: '机构',
            component: <CompanyDepartPlus />
        },
        {
            field: 'userName',
            label: '员工',
            config: {
                initialValue: employeeName
            },
            component: <Input placeholder="输入姓名" />
        },
        {
            field: 'date',
            config: {
                initialValue: {
                    range: [
                        typeof startTime === 'undefined' ? moment().startOf('month') : moment(startTime),
                        typeof endTime === 'undefined' ? moment() : moment(endTime)
                    ],
                    quarter: quarter ? Number(quarter) : 1,
                    type: typeof dateType === 'undefined' ? 'month' : dateType
                }
            },
            component: (
                <DateRange
                    range
                    dateTypes={[
                        {
                            label: '本周',
                            type: 'week'
                        },
                        {
                            label: '本月',
                            type: 'month'
                        },
                        {
                            label: '本年',
                            type: 'year'
                        }
                    ]}
                />
            )
        }
    ];

    const columns = [
        {
            title: '工号',
            dataIndex: 'userNo',
            key: 'userNo'
        },
        {
            title: '姓名',
            dataIndex: 'employeeName',
            key: 'employeeName'
        },
        {
            title: '组织机构',
            dataIndex: 'departmentName',
            key: 'departmentName'
        },
        {
            title: '日期',
            dataIndex: 'signDate',
            key: 'signDate'
        },
        {
            title: '签到时间',
            dataIndex: 'signInTime',
            key: 'signInTime'
        },
        {
            title: '签到状态',
            dataIndex: 'signInStatusNick',
            key: 'signInStatusNick',
            render(text, record) {
                return <span className={record.signInStatus === 5 ? null : 'text-danger'}>{text}</span>;
            }
        },
        {
            title: '签退时间',
            dataIndex: 'signOutTime',
            key: 'signOutTime'
        },
        {
            title: '签退状态',
            dataIndex: 'signOutStatusNick',
            key: 'signOutStatusNick',
            render(text, record) {
                return <span className={record.signOutStatus === 5 ? null : 'text-danger'}>{text}</span>;
            }
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 120,
            render: (text, record) => (
                <span>
                    <AuthComponent code={authCode('detail')}>
                        <LinkTo
                            to="/office/personnelManagement/attendance/timetag/attendRecord/clockRecord"
                            query={{
                                id: record.employeeCode,
                                name: record.employeeName,
                                signDate: record.signDate
                            }}
                        >
                            查看打卡记录
                        </LinkTo>
                    </AuthComponent>
                </span>
            )
        }
    ];

    const getParams = _query => {
        const { companyDepart, date = { range: [] }, userName: rangeUserName } = getFieldsValue();
        const payload = {
            companyCode: companyDepart?.companyId,
            departmentCode: companyDepart?.departmentId,
            startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD') : '',
            endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD') : '',
            status: '',
            employeeName: rangeUserName || '',
            pageNo: query.pageNo || 1,
            pageSize: query.pageSize || 10,
            ..._query
        };
        return payload;
    };

    const fetchList = _query => {
        dispatch(
            deepTrim({
                type: 'attendRecord/fetchList',
                payload: getParams(_query)
            })
        );
    };

    React.useEffect(() => {
        fetchList();
    }, []);

    const handleSubmit = async e => {
        const { companyDepart, userName: queryUsername, date = { range: [] } } = form.getFieldsValue();
        e.preventDefault();
        const finalQuery = {
            ...query,
            companyId: companyDepart && companyDepart.companyId,
            departmentId: companyDepart && companyDepart.departmentId,
            dateType: date.type,
            employeeName: queryUsername,
            startTime: date.range && date.range[0] ? moment(date.range[0]).format('YYYY-MM-DD') : '',
            endTime: date.range && date.range[1] ? moment(date.range[1]).format('YYYY-MM-DD') : '',
            pageNo: 1
        };
        updateQuery(match.path, finalQuery);
        fetchList(finalQuery);
    };

    const changeCurrent = async pagination => {
        const finalQuery = {
            ...query,
            pageNo: pagination.current,
            pageSize: pagination.pageSize
        };
        await updateQuery(match.path, finalQuery);
        fetchList(finalQuery);
    };

    const handleExport = () => {
        const { pageNo, pageSize, ...other } = getParams();
        download({
            getData: () =>
                dispatch({
                    type: 'attendRecord/fetchExport',
                    payload: deepTrim(other)
                })
        });
    };

    return (
        <PageHeaderWrapper>
            <Fragment>
                <Form layout="inline" onSubmit={handleSubmit}>
                    <Card
                        bordered={false}
                        title="检索条件"
                        extra={
                            <Fragment>
                                <Button type="primary" htmlType="submit">
                                    {locale('form.search', false)}
                                </Button>
                                <AuthComponent code={authCode('history')}>
                                    <Button
                                        style={{ marginLeft: 16 }}
                                        onClick={() =>
                                            history.push({
                                                pathname:
                                                    '/office/personnelManagement/attendance/timetag/attendRecord/clockRecord'
                                            })
                                        }
                                    >
                                        打卡记录
                                    </Button>
                                </AuthComponent>
                                <AuthComponent code={authCode('export')}>
                                    <Button
                                        style={{ marginLeft: '5px' }}
                                        onClick={handleExport}
                                        disabled={loading.effects['attendRecord/fetchList']}
                                    >
                                        导出
                                    </Button>
                                </AuthComponent>
                            </Fragment>
                        }
                    >
                        <QuickForm form={form} config={config} />
                    </Card>
                </Form>
                <Card bordered={false} style={{ marginTop: '12px' }}>
                    <Table
                        bordered={false}
                        columns={columns}
                        scroll={{ x: 'max-content' }}
                        loading={loading.models.attendRecord}
                        dataSource={data}
                        onChange={changeCurrent}
                        rowKey="id"
                        pagination={false}
                    />
                    <Pagination
                        onChange={changeCurrent}
                        pageSize={query.pageSize}
                        current={query.pageNo}
                        total={attendRecord.pagination.total}
                        loading={loading.models.attendRecord}
                    />
                </Card>
            </Fragment>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ attendRecord, loading }) => ({
        attendRecord,
        loading
    }))(Form.create()(List))
);
